package cumeo89.chii.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ClosingEvent;
import com.google.gwt.user.client.Window.ClosingHandler;
import com.google.gwt.user.client.ui.PopupPanel;

import cumeo89.chii.client.entry.EntryModel;
import cumeo89.chii.client.form.DialogBoxes;
import cumeo89.chii.client.form.MainForm;
import cumeo89.chii.client.mw.MediaWiki;
import cumeo89.chii.client.mw.Page;
import cumeo89.chii.client.ui.UIUtil;
import cumeo89.chii.client.util.AsyncCallback;
import cumeo89.chii.client.wikt.FakeWiktionary;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Chii implements ClosingHandler {

	private static final Chii INSTANCE = new Chii();

	public static Chii get() {
		return INSTANCE;
	}

	private List<ChiiListener> listeners = new ArrayList<ChiiListener>();
	private MainForm main = new MainForm(this);
	private MediaWiki mediaWiki = new FakeWiktionary();
	// data
	private Page page = null;
	private EntryModel model = null;

	private Chii() {
		Window.addWindowClosingHandler(this);
	}

	public MediaWiki getMediaWiki() {
		return mediaWiki;
	}

	public Page getPage() {
		return page;
	}

	public EntryModel getModel() {
		return model;
	}

	public void load(String entryTitle, final AsyncCallback<Page> callback) {
		final PopupPanel progressPopup = DialogBoxes
				.showProgressPopup("Đang tải dữ liệu, xin hãy chờ chút...");
		Chii.get().getMediaWiki().edit(entryTitle, new AsyncCallback<Page>() {

			public void onFailure(Throwable caught) {
				page = null;
				model = null;
				progressPopup.hide();
				if (callback != null) {
					callback.onFailure(caught);
				}
			}

			public void onSuccess(Page result) {
				page = result;
				textToModel();
				for (ChiiListener lis : listeners) {
					lis.entryLoaded(Chii.this);
				}
				progressPopup.hide();
				if (callback != null) {
					callback.onSuccess(result);
				}
			}

		});
	}

	public void reload(AsyncCallback<Page> callback) {
		load(page.getTitle(), callback);
	}

	public void textToModel() {
		if (model == null) {
			model = new EntryModel();
		}
		model.setDocument(mediaWiki.parse(page.getTitle(), page.getContent()));
	}

	public void modelToText() {
		page.setContent(mediaWiki.toWikitext(model.getDocument()));
	}

	public void shutdown() {
		UIUtil.closeWindow();
	}

	public void addChiiListener(ChiiListener lis) {
		listeners.add(lis);
	}

	public void removeChiiListener(ChiiListener lis) {
		listeners.remove(lis);
	}

	public void onWindowClosing(ClosingEvent event) {
		for (ChiiListener lis : listeners) {
			String mess = lis.chiiWillShutDown(this);
			if (mess != null && mess.length() > 0) {
				event.setMessage(mess);
				return;
			}
		}
		for (ChiiListener lis : listeners) {
			lis.chiiShutedDown(this);
		}
	}

}